package com.ysw.rpc.client.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.ysw.rpc.client.component.ChannelComponent;
import com.ysw.rpc.client.enums.ConnectionEnum;
import com.ysw.rpc.client.utils.ChannelUtil;
import lombok.extern.slf4j.Slf4j;

import static com.ysw.rpc.client.utils.CacheUtil.getServerChannelCache;

/**
 * @author YinShangwen
 * @since 2023/4/18 11:50
 */
@Slf4j
public class ClientInitializerConfig extends AbstractClientInitializerConfig {
    private final ClientProperties clientProperties;
    private final ChannelComponent channelComponent;

    public ClientInitializerConfig(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties, ClientProperties clientProperties, ChannelComponent channelComponent) {
        super(nacosServiceManager, nacosDiscoveryProperties);
        this.clientProperties = clientProperties;
        this.channelComponent = channelComponent;
    }

    @Override
    public void init() {
        channelComponent.init();
        ChannelUtil.setChannelComponent(channelComponent);
    }

    @Override
    public void destroyHandler() {
        if (ConnectionEnum.isSingleLong(clientProperties.getConnectionType())) {
            getServerChannelCache().keySet().forEach(channelComponent::unsubscribe);
        }
    }
}
